#include "client_login.h"

client_login::client_login(socket* father,QWidget *parent)
	: QWidget(parent),
	client(father),
	isconnected(false)
{
	ui.setupUi(this);
	connect(client, &socket::connected, this, &client_login::iscon);
	connect(client, &socket::disconnected, this, &client_login::discon);
	this->show();
}

client_login::~client_login()
{
}

void client_login::login() {
	const QString username = ui.username->text();
	if (socket::critical(this, username) ){
		return;
	}
	QString IP(ui.IP_1->text());
	IP.append('.');
	IP.append(ui.IP_2->text());
	IP.append('.');
	IP.append(ui.IP_3->text());
	IP.append('.');
	IP.append(ui.IP_4->text());
	QString port(ui.port->text());
	client->connectToHost(IP, port.toInt());
	client->waitForConnected(5000);
	if (!isconnected) {
		QMessageBox::warning(this, QString("Error"), QString("Connection failed. Check that the IP address and port are correct."), 
			QMessageBox::Ok, QMessageBox::NoButton);
		return;
	}
	client->send_name(username);
	emit startup(username,IP);
	this->hide();
}

void client_login::closeEvent() {
	exit(0);
}

void client_login::iscon()
{
	isconnected = true;
}

void client_login::discon()
{
	QMessageBox::information(this, QString("Error"), QString("Connection has shut down."),
		QMessageBox::Ok, QMessageBox::NoButton);
	//isconnected = false;
	client->close();
	exit(0);
}
